package eppic.pkg;

import android.app.Activity;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemSelectedListener;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.entity.StringEntity;
import org.json.*;
import java.io.InputStream;



public class ExportProjectActivity extends Activity {

	public  ExportSpinnerListener methodSelected = new ExportSpinnerListener();
	
	public Project project;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exportproject);
        
        //Get the project to be exported
        Bundle extras = getIntent().getExtras();
        int id = extras.getInt("project_id");
        project = new Project(id, this);
        
        //Send to email address setup
        TextView to = (TextView) findViewById(R.id.to);
        if(project.client_id > 0)
        {
        	Client parent = new Client(project.client_id,this);
            to.setText(parent.email);
        }
        
        //'Export Type Spinner' Setup
        Spinner method = (Spinner) findViewById(R.id.methods);
        ArrayAdapter<CharSequence> methodList = ArrayAdapter.createFromResource(
                this, R.array.export_methods, android.R.layout.simple_spinner_item);
        methodList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        method.setAdapter(methodList);
        method.setOnItemSelectedListener(methodSelected);

        
        
    }
    
    public void exportProject(View view)
    {
    	TextView emailAddr = (TextView) findViewById(R.id.to);
    	final String email = emailAddr.getText().toString();
    	
    	Thread t = new Thread(){
            public void run() {
                    Looper.prepare(); //For Preparing Message Pool for the child Thread
                    HttpClient client = new DefaultHttpClient();
                    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                    HttpResponse response;
                    JSONObject json = new JSONObject();
                    try{
                        HttpPost post = new HttpPost("http://eppic.net/hourstracker.php");
                        
                        json.put("to", email);
                        json.put("subject", "New Data Exported from Hours Tracker");
                        
                        json.put("type", "project");
                        json.put("method", methodSelected.selected);
                        
                        json.put("name", project.name);
                        json.put("rate", project.rate);
                        
                        //Create Logs array
                    	JSONArray jLogsStart = new JSONArray();
                    	JSONArray jLogsEnd = new JSONArray();
                    	Log[] logs = project.getLogs(getApplicationContext());
                    	
                    	if(logs.length > 0)
                    	{
                    		for(int i = 0; i <logs.length; i++)
                    		{
                    			jLogsStart.put(logs[i].start);
                    			jLogsEnd.put(logs[i].end);
                    		}
                    	}
                        json.put("logsStart", jLogsStart);
                        json.put("logsEnd", jLogsEnd);
                        
                        //Create Expenses Array
                        JSONArray jExpName = new JSONArray();
                    	JSONArray jExpCost = new JSONArray();
                    	Expense[] expz = project.getExpenses(getApplicationContext());
                        
                    	if(expz.length > 0)
                    	{
                    		for(int i = 0; i <expz.length; i++)
                    		{
                    			jExpName.put(expz[i].name);
                    			jExpCost.put(expz[i].cost);
                    		}
                    	}
                    	json.put("expName", jExpName);
                        json.put("expCost", jExpCost);
                        
                        StringEntity se = new StringEntity( "JSON: " + json.toString());  
                        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                        post.setEntity(se);
                        response = client.execute(post);
                        /*Checking response */
                        if(response!=null){
                            InputStream in = response.getEntity().getContent(); //Get the data in the entity

                            if(in.read() == -1)
                            {
                            	Toast.makeText(getApplicationContext(), "Failed to send Message. Please check the email address and try again.", Toast.LENGTH_LONG).show();
                            }
                            else
                            {
                            	Toast.makeText(getApplicationContext(), "Message Successfully sent to: \n"+email+".", Toast.LENGTH_LONG).show();
                            	finish();
                            }
                            
                        }
                    }
                    catch(Exception e){
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Error, Cannot Establish a Connection.", Toast.LENGTH_SHORT).show();
                    }
                    Looper.loop(); //Loop in the message queue
                }
            };
            t.start();      
    	
    }
    
    public void goBack(View view) {
    	finish();
    }

    
    //This class handles the actions of the Method Spinner
    public class ExportSpinnerListener implements OnItemSelectedListener {

    	public String selected;
    	
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
        {
        	this.selected = parent.getItemAtPosition(pos).toString();
        }

        public void onNothingSelected(AdapterView parent) {
          // Do nothing.
        }
    }
    
}